﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class iframe : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //token=abc123
            string token = Request.QueryString.Get("token")?.ToString();
            string userId = Request.QueryString.Get("userid")?.ToString();
            string userName = Request.QueryString.Get("username")?.ToString();
            string appKey = Request.QueryString.Get("appkey")?.ToString();
            string appSecret = Request.QueryString.Get("appSecret")?.ToString();

            string returnUrl = Request.QueryString.Get("ReturnUrl")?.ToString();
            if (!string.IsNullOrWhiteSpace(returnUrl))
            {
                returnUrl = Server.HtmlDecode(returnUrl);
            }
            string loginUrl = Request.QueryString.Get("LoginUrl")?.ToString();
            string urlParameter = "?CheckOnline=true";
            string removetoken = Request.QueryString.Get("removetoken")?.ToString();
            //清除sso 网页中的token和userid
            if (!string.IsNullOrWhiteSpace(removetoken) && removetoken == "true")
            {
                if (!string.IsNullOrWhiteSpace(Request.Cookies["token"]?.Value) &&
                    !string.IsNullOrWhiteSpace(Request.Cookies["userid"]?.Value) &&
                    !string.IsNullOrWhiteSpace(Request.Cookies["username"]?.Value))
                {
                    ClearCookie();
                    RedirectParent2Url(returnUrl, string.Empty);
                }
            }
            //如果不是注销时申请清除cookie的
            else
            {
                //如果子系统调用此页面写Cookie到SSO页面
                if (!string.IsNullOrEmpty(appKey) && !string.IsNullOrEmpty(appSecret) &&
                    !string.IsNullOrEmpty(token) && !string.IsNullOrWhiteSpace(userId) &&
                    !string.IsNullOrWhiteSpace(userName))
                {
                    
                    Response.Headers.Add("P3P", "CP=CAO PSA OUR");
                    /*
                    HttpCookie cookieAppKey = new HttpCookie($"appkey_{appKey}");
                    cookieAppKey.Name = "appKey";
                    cookieAppKey.Value = appKey;
                    Response.Cookies.Set(cookieAppKey);
                    */
                    HttpCookie cookieToken = new HttpCookie("token");
                    cookieToken.Name = "token";
                    cookieToken.Value = token;
                    Response.Cookies.Set(cookieToken);

                    HttpCookie cookieUserId = new HttpCookie("userid");
                    cookieUserId.Name = "userid";
                    cookieUserId.Value = userId;
                    Response.Cookies.Set(cookieUserId);

                    HttpCookie cookieUserName = new HttpCookie("username");
                    cookieUserName.Name = "username";
                    cookieUserName.Value = userName;
                    Response.Cookies.Set(cookieUserName);
                    //跳转到登录后页面
                    string str = "?token=" + token + "&userid=" + userId +
                                              "&username=" + userName + "&LoginStatus=success";
                    RedirectParent2Url(returnUrl, str);
                }
                //如果调用此页是为了检测本地是否已经登录
                else
                {
                    string cookieToken = Request.Cookies.Get("token")?.Value;
                    string cookieUserId = Request.Cookies.Get("userid")?.Value;
                    string cookieUserName = Request.Cookies.Get("username")?.Value;
                    //如果检测到cookie中有token和userid
                    if (!string.IsNullOrWhiteSpace(cookieToken) &&
                        !string.IsNullOrWhiteSpace(cookieUserId) &&
                        !string.IsNullOrWhiteSpace(cookieUserName))
                    {
                        //做token验证，调用检查在线的api接口
                        var isOnline = CheckOnline(appKey, cookieToken, cookieUserId, appSecret);
                        if (isOnline > 0)
                        {
                            //确认有cookie，跳转到登录后页面
                            if (isOnline == 1)
                            {
                                string str = $"?token={cookieToken}&userid={cookieUserId}&username={cookieUserName}&LoginStatus=AlreadyLogin";
                                RedirectParent2Url(returnUrl, str);
                            }
                            else if (isOnline == 2)
                            {
                                string str = $"?token={cookieToken}&userid={cookieUserId}&username={cookieUserName}&LoginStatus=LoginInOtherPlace";
                                RedirectParent2Url(returnUrl, str);
                            }
                        }
                        //确认没有登录，先移除cookie,再跳转到登录页面
                        else
                        {
                            ClearCookie();
                            RedirectParent2Url(loginUrl, urlParameter);
                        }
                    }
                    //如果检测到cookie中没有token,就直接跳转去子系统的登录页面
                    else
                    {
                        ClearCookie();
                        RedirectParent2Url(loginUrl, urlParameter);
                    }
                }
            }



        }

        /// <summary>
        /// 重定向iframe到url
        /// </summary>
        /// <param name="url">网址</param>
        public void RedirectParent2Url(string url, string urlParameter)
        {
            string script = $"window.parent.location.href='{url}{urlParameter}'";
            if (!string.IsNullOrWhiteSpace(url))
            {
                ClientScript.RegisterStartupScript(this.GetType(), "parent", script, true);
            }
        }

        public int CheckOnline(string appKey, string token, string userId, string appSecret)
        {
            int isOnline = 0;
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri(ConfigHelper.APIHost);
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("appliation/json"));
            UserInfo user = new UserInfo()
            {
                AppKey = appKey,
                AppSecret = appSecret,
                Ip = Request.UserHostAddress,
                UserId = userId,
                Token = token,
            };
            HttpResponseMessage response = client.PostAsJsonAsync("api/sso/checkonline", user).Result;
            if (response.IsSuccessStatusCode)
            {
                Result obj = new Result();
                var result = response.Content.ReadAsAsync<Result>().Result;
                if (result.Code == 0)
                {
                    isOnline = 1;
                }
                else if (result.Code == 2)
                {
                    isOnline = 2;
                }
            }
            return isOnline;
        }

        public void ClearCookie()
        {
            Response.Cookies["token"].Expires = DateTime.Now.AddDays(-1);
            Response.Cookies.Remove("token");
            Response.Cookies["userid"].Expires = DateTime.Now.AddDays(-1);
            Response.Cookies.Remove("userid");
            Response.Cookies["username"].Expires = DateTime.Now.AddDays(-1);
            Response.Cookies.Remove("username");
        }

    }
}